package com.permission.common;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 获取Spring上下文工具
 * @author jing
 * 
 *  需要被Spring管理，所以使用@Component注解
 *  @Component 对那些比较中立的类进行注释
 */
@Component
public class ApplicationContextHelper implements ApplicationContextAware{

	private static ApplicationContext applicationContext;
	
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		applicationContext = context;
	}
	
	public static <T> T popBean(Class<T> clazz){
		if(applicationContext == null){
			return null;
		}
		//如果applicationContext不为空，则取出clazz
		return applicationContext.getBean(clazz);
	}
	
	//可能以一个String类型过来的
	public static <T> T popBean(String name,Class<T> clazz){
		if(applicationContext == null){
			return null;
		}
		//如果applicationContext不为空，则取出clazz
		return applicationContext.getBean(name,clazz);
	}
	
	/*
	 * 该类配置完成之后需要在Spring里面去配置。
	 * 我们在springmvc.xml里面添加相应的配置，并且禁止懒加载
	 * <bean class="com.permission.common.ApplicationContextHelper" />
	 */
}
